// import AMap from "AMap";
import electricFenceMng from "@/pages/electricFence/electricFenceMng/model";
import { Button, message, Spin } from "antd";
import { connect } from "dva";
import { routerRedux } from "dva/router";
import PropTypes from "prop-types";
import React, { PureComponent } from "react";
import styles from "./index.less";
import moment from 'moment';

const proZoom = {
    // 420000: 7, // 湖北
    540000: 6, // 西藏
    650000: 5, // 新疆
    630000: 6, // 四川
    150000: 5, // 内蒙
    620000: 6, // 甘肃
    310000: 8, // 上海
  };

@connect((state) => ({
  menu: state.menu,
  overdueCar: state.overdueCar,
}))
export default class OverdueCarLocation extends PureComponent {
  static contextTypes = {
    authButton: PropTypes.array,
  };
  //查询行政区授信车辆数量
  getDataSource = async () => {
    return new Promise((resolve) => {
      this.props.dispatch({
        type: "overdueCar/postDataWithRes",
        payload: {
          url: "/mscreditbusiness/vehicle/credit/listForMap",
          type: "overdue",
          level:
            this.type === 0
              ? "country"
              : this.type === 1
              ? "province"
              : "city",
            adCode:  this.type === 0
            ? undefined
            : this.type === 1
            ? this.province.adCode
            : this.city.adCode,
          // adCode: this.province ? this.province.adCode : undefined,
        },
        callback: (response) => {
          if (response && response.statusCode == "0") {
            resolve(
              response.data
                .map((e) => ({ ...e, adCode: parseInt(e.adCode || 0) }))
                .sort((a, b) => a.overdueCount - b.overdueCount)
            );
          } else {
            message.error(response.statusMessage);
          }
        },
      });
    });

    return [
      520000, 540000, 530000, 500000, 360000, 340000, 510000, 350000, 430000,
      420000, 420100, 429004, 420105, 420111, 410000, 330000, 640000, 650000,
      440000, 370000, 450000, 630000, 320000, 140000, 460000, 310000, 110000,
      130000, 230000, 220000, 210000, 150000, 120000, 620000, 610000, 710000,
      810000, 820000,
    ]
      .map((adCode) => ({
        adCode,
        adName: `test-${adCode}`,
        level: "country",
        total: 100 * Math.random(),
        riskCount: 10,
        overdueCount: 32,
      }))
      .sort((a, b) => a.total - b.total);
  };

  state = {
    loading: false,
    mapFields: [],
    creditTypeOptions:[],
  };

  type = 0; // 显示省市区类型
  province = null; // 当前选择的省
  city = null; //当前选取的城市（地市级）
  provinceArea = null;
  map = null; // 地图实例
  infoWindow = null;
  infoWindow2 = null;
  dataSource = [];
  // labelsLayer = null;
  // repaymentStatus = ["还款中", "已逾期", "已结清", "融资已到期"];
    // 预警车 / 授信车 共用标记
  isWarningCarMap = !!sessionStorage.getItem("isWarningCarMap");
  
  initMapByLoading = () => {
    if (this.type === 1 && !this.province) {
      message.warning("请选择一个省份");
      this.type = 0;
      return;
    }
    if (this.type === 2 && !this.city) {
      message.warning("请选择一个城市");
      this.type = 1;
      return;
    }
    this.setState({ loading: true });
    this.initMap()
      .then(() =>
        // 区县级显示会慢, 官方demo也慢, 给个loading
        this.type === 2
          ? new Promise((a) => setTimeout(a, 2000))
          : Promise.resolve()
      )
      .finally(() => this.setState({ loading: false }));
  };
  
  initMapInstance = () => {
    if (!this.map) {
      // 地图全局实例
      this.map = new AMap.Map("container", {
        // zooms: [4, 9]
      });

      // 地图点击事件, 通过点击位置确认点击省份
      this.map.on("click", (ev) => {
        if (!this.provinceArea) {
          return;
        }
        const props = this.provinceArea.getDistrictByContainerPos(ev.pixel);

        if (props) {
          const currentProvince =
            this.dataSource.find((e) => e.adCode === props.adcode) || {};
          if (currentProvince) {
            if (!this.type) {
              currentProvince.lnglat = ev.lnglat;
              this.province = currentProvince;
            }
            if (this.type == 1) {
              currentProvince.lnglat = ev.lnglat;
              this.city = currentProvince;
            }
            // 弹框
            this.showInfoWindow(currentProvince, props.NAME_CHN, ev.lnglat);
          }
        }
      });
    }
  };

      initMap = async () => {
        this.initMapInstance();
        if (!this.type) {
          this.map.setZoomAndCenter(4, [106.244362, 33.550679], true);
        } else if(this.type === 1){
          this.map.setZoomAndCenter(
            proZoom[this.province.adCode] || 7,
            this.province.lnglat,
            true
          );
        } else {
          this.map.setZoomAndCenter(
            proZoom[this.city.adCode] || 9,
            this.city.lnglat,
            true
          );
        }
        // if (!this.type) {
        //   this.map.setZoomAndCenter(4, [106.244362, 33.550679], true);
        // } else {
        //   this.map.setZoomAndCenter(
        //     proZoom[this.province.adCode] || 7,
        //     this.province.lnglat,
        //     true
        //   );
        // }
        if (this.labelsLayer) {
          this.labelsLayer.clear();
        }
    
        if (this.infoWindow) {
          this.infoWindow.close();
        }
    
        if (this.infoWindow2) {
          this.infoWindow2.close();
        }
    
        if (this.provinceArea) {
          this.provinceArea.setMap(null);
        }
        this.dataSource = await this.getDataSource();
        // 区域按数量颜色填充
        this.provinceArea = new AMap.DistrictLayer.Province({
          zIndex: 50,
          depth: this.type,
          adcode: (() => {
            if (this.type === 1) {
              return [this.province.adCode];
            } 
            else if(this.type === 2){
              return [this.city.adCode];
            }else {
              return this.dataSource.map((e) => e.adCode);
            }
          })(),
          styles: {
            "province-stroke": "orange",
            "city-stroke": "orange", // 中国地级市边界
            "county-stroke": "orange", // 中国区县边界
            fill: (props) => this.colorFill(props, this.dataSource),
          },
        });
        this.provinceArea.setMap(this.map);
      };

    colorFill = (props, list) => {
    const current = list.find((e) => e.adCode === props.adcode);
    const valueKey = "overdueCount";

    if (!current || !current[valueKey]) {
      // 没有找到值 或者 找的值不存在
      return "white";
    }
    const MAX = 255;
    const MIN = 30;
    const max = list[list.length - 1][valueKey] || 0;
    const min = list[0][valueKey] || 0;
    if (min === max) {
      // 全部值都一样, 按最深色给值
      return `rgb(${MIN},${MIN},255)`;
    }
    // 剩下的按 80 - 200 做差值计算
    let rg =
      MAX -
      MIN -
      Math.floor(((current[valueKey] - min) / (max - min)) * (MAX - MIN));
    return "rgb(" + rg + "," + rg + ",255)";
  };
  
  showInfoWindow = (nums, title, pos) => {
    let content = [
      `<div style=\"text-align:center\">${title}</div>`,
      // `<div>授信车辆: ${nums.total || 0}</div>`,
      // `<div>预警车辆: ${nums.riskCount || 0}</div>`,
      `<div>逾期车辆: ${nums.overdueCount || 0}</div>`,
    ];
    this.infoWindow = new AMap.InfoWindow({
      content: content.join(""),
    });
    this.infoWindow.open(this.map, pos);
  }
  repaymentStatus = ["还款中", "已逾期", "已结清", "融资已到期"];
  showInfoWindow2 = (current, pos) => {
    global.gotoDetail = () => {
      sessionStorage.setItem("vin", JSON.stringify(current.vin));
      sessionStorage.setItem("backPathData", JSON.stringify(current));
      sessionStorage.setItem("typeOption", JSON.stringify(this.state.creditTypeOptions));
      sessionStorage.setItem(
        "backPath",
           "/creditPlatform/overdueCarMap"
      );
      this.props.dispatch(
        routerRedux.push({
          pathname: (() => {
            if (current.repaymentStatus === 1) {
              // 逾期
              return "/creditPlatform/overdueCarDetail";
            } else if (current.riskWarnStatus) {
              // 预警
              // return "/thirdOrgCreditVehicle/thirdOrgCreditVehicleWarningCarDetail";
            } else if (current.riskStatus) {
              // 锁车, 跛行
            } else {
              // 授信
            }
            return "/creditPlatform/overdueCarDetail" 
           
          })(),
        })
      );
    };

    // 下划线转驼峰
    function toCamel(str) {
      return str.replace(/([^_])(?:_+([^_]))/g, function ($0, $1, $2) {
        return $1 + $2.toUpperCase();
      });
    }
    let content = this.state.mapFields.map((i) => {
      const item = i;
      const key = toCamel(i.column);
      const value = current[key];
      const text = value;
      if (item.type === 4) {
        if (typeof text == "number") {
          return `<div>${i.name}:${
            text ? moment(text).format("YYYY-MM-DD") : ""
          }</div>`;
        } else {
          return `<div>${i.name}:${
            text ? moment(text, "YYYY-MM-DD").format("YYYY-MM-DD") : ""
          }</div>`;
        }
      }
      if (item.type === 5) {
        if (typeof text == "number") {
          return `<div>${i.name}:${
            text ? moment(text).format("HH:mm:ss") : ""
          }</div>`;
        } else {
          return `<div>${i.name}:${
            text ? moment(text, "HH:mm:ss").format("HH:mm:ss") : ""
          }</div>`;
        }
      }
      if (item.type === 6) {
        if (typeof text == "number") {
          return `<div>${i.name}:${
            text ? moment(text).format("YYYY-MM-DD HH:mm:ss") : ""
          }</div>`;
        } else {
          return `<div>${i.name}:${
            text
              ? moment(text, "YYYY-MM-DD HH:mm:ss").format(
                  "YYYY-MM-DD HH:mm:ss"
                )
              : ""
          }</div>`;
        }
      }
      if (item.type === 7) {
        return `<div>${i.name}: <a href="${value}" target="_blank" >${value}</a></div>`;
      }

      if (item.name === "是否支持跛行") {
        return `<div>${i.name}: ${text == 1 ? "是" : "否"}</div>`;
      }
      if (item.name === "车辆预警状态") {
        let v = "";
        if (text == "0") {
          v = "未预警";
        } else if (text == "1") {
          v = "预警";
        } else {
          v = text;
        }
        return `<div>${i.name}: ${v}</div>`;
      }
      if (item.name === "驾驶状态") {
        let v = "";
        if (text == "") {
          v = "行驶中";
        } else if (text == "0") {
          v = "熄火";
        } else if (text == "2") {
          v = "点火";
        } else {
          v = "";
        }
        return `<div>${i.name}: ${v}</div>`;
      }
      if (item.name === "还款状态") {
        let v = "";
        if (text == "0") {
          v = "还款中";
        } else if (text == "1") {
          v = "已逾期";
        } else if (text == "2") {
          v = "已结清";
        } else {
          v = "未知";
        }
        return `<div>${i.name}: ${v}</div>`;
      }
      if (item.name === "车辆风控状态") {
        let v = "";
        if (text === "0") {
          v = "正常行驶";
        } else if (text === "1") {
          v = "锁车";
        } else if (text === "2") {
          v = "跛行";
        } else {
          v = text;
        }
        return `<div>${i.name}: ${v}</div>`;
      }

      if (item.name === "车机告警类型") {
        let v = "";
        if (text == 0) {
          v = "暂不支持";
        } else if (text == 1) {
          v = "不可配置";
        } else if (text == 2) {
          v = "可配置";
        } else {
          v = text;
        }
        return `<div>${i.name}: ${v}</div>`;
      }
      if (item.name === "车机告警状态") {
        let v = "";
        if (text == 0) {
          v = "正常";
        } else if (text == 1) {
          v = "车机告警";
        } else {
          v = text;
        }
        return `<div>${i.name}: ${v}</div>`;
      }
      if (item.name === "授信类型") {
        let v = "";
        if (text == "0") {
          v = "经销商";
        } else if (text == "1") {
          v = "个人";
        } else {
          v = text;
        }
        return `<div>${i.name}: ${v}</div>`;
      }
      if (key === "vin") {
        return `<div>${
          i.name
        }: <a style="color: blue" onclick="gotoDetail();">${
          value ? value : ""
        }</a></div>`;
      }
      return `<div>${i.name}: ${value !== null ? value : ""}</div>`;
    });
    this.infoWindow2 = new AMap.InfoWindow({
      content: content.join(""),
    });
    this.infoWindow2.open(this.map, pos);
    this.map.setZoomAndCenter(20, pos, true);
  }

  handleOnReturn = () => {
    const backPath = sessionStorage.getItem("backPathMap");
    this.props.dispatch(
      routerRedux.push({
        pathname: backPath,
      })
    );
  }

  getFields = async () => {
    return new Promise((resolve) => {
      const addPreinstall = (columns) => {
        return columns.map((i) => {
          const sameTitle = columns.some(
            (j) => j.name === i.name && i.fieldId !== j.fieldId
          );
          if (sameTitle && i.fieldId) {
            i.name = `${i.name}(预设)`;
          }
          return i;
        });
      };
      // const businessCode = this.isWarningCarMap ? "warning" : "credit";
      this.props.dispatch({
        // 更多筛选数据
        type: "overdueCar/postDataWithRes",
        payload: {
          url: `/mscreditbusiness/credit/merchant/field/scenelist?menu=overdue&scene=map`,
        },
        callback: (response) => {
          if (response && response.statusCode == "0") {
            if (response.data && response.data.length > 0) {
              resolve(addPreinstall(response.data));
            } else {
              resolve([]);
            }
          } else {
            resolve([]);
            message.error(response.statusMessage);
          }
        },
      });
    });
  };

      //获取车辆位置
      getCarPos = async () => {
        return new Promise((resolve) => {
          this.props.dispatch({
            type: "overdueCar/postDataWithRes",
            payload: {
              url: "/mscreditbusiness/vehicle/position/road/list",
              businessCode: "overdue",
            },
            callback: (response) => {
              if (response && response.statusCode == "0") {
                resolve(response.data);
              } else {
                message.error(response.statusMessage);
              }
              resolve([]);
            },
          });
        });
    }
      labelsLayer = null;
      handleClickStreet = async () => {
        this.initMapInstance();
        if (this.infoWindow2) {
          this.infoWindow2.close();
        }
    
        if (this.provinceArea) {
          this.provinceArea.setMap(null);
        }
        if (this.labelsLayer) {
          this.labelsLayer.clear();
        }
    
        if (this.infoWindow) {
          this.infoWindow.close();
        }
        
        this.province = null;
        this.city = null;
        // 防卡顿
        await new Promise((a) => setTimeout(a, 100));
        const carPos = await this.getCarPos();
        const mapFields = await this.getFields();
        this.setState({
          mapFields,
        });
        const labels = carPos.map((car) => {
            if (!car.lng || !car.lat) {
              return null;
            }
            let e = this.bd_decrypt(car);
            let img = "";
            if (e.riskStatus !== 0) {
              img = "hui";
            } else if (e.repaymentStatus === "1") {
              img = "red";
            } else if (e.riskWarnStatus !== "0") {
              img = "yellow";
            } else {
              img = "blue";
            }
            const label = new AMap.LabelMarker({
              name: "test",
              position: [e.lng, e.lat],
              icon: {
                type: "image",
                image: require(`@/assets/${img}_car.png`),
                size: [52, 26],
                anchor: "center",
              },
            });
    
            label.on("click", (item) => {
              this.showInfoWindow2(e, [e.lng, e.lat]);
            });
    
            return label;
          })
          .filter((e) => e);
    
        this.labelsLayer = new AMap.LabelsLayer({
          zooms: [3, 20],
          zIndex: 1000,
          collision: false,
          allowCollision: true,
        });
        this.labelsLayer.add(labels);
        this.map.add(this.labelsLayer);
        this.map.setZoomAndCenter(4, [106.244362, 33.550679]);
      }
  
      bd_decrypt = (item) => {
        const { lng, lat } = item;
        let X_PI = (Math.PI * 3000.0) / 180.0;
        let x = lng - 0.0065;
        let y = lat - 0.006;
        let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * X_PI);
        let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * X_PI);
        let gg_lng = z * Math.cos(theta);
        let gg_lat = z * Math.sin(theta);
        return { ...item, lng: gg_lng, lat: gg_lat };
      }
  

      componentDidMount() {
        let backPathData = sessionStorage.getItem("backPathData");
        const typeOption = sessionStorage.getItem("typeOption");
        this.setState({ creditTypeOptions: JSON.parse(typeOption)});
        if (backPathData) {
          sessionStorage.setItem("backPathData", "");
          backPathData = JSON.parse(backPathData);
          this.handleClickStreet();
          setTimeout(
            () =>
              this.showInfoWindow2(backPathData, [
                backPathData.lng,
                backPathData.lat,
              ]),
            500
          );
          return;
        }
        this.initMap();
      }
  render() {
    const {
      requestPositionTimes,
      issuedLocationBtnLoading,
      address,
      countDown,
    } = this.state;
    const {menu: { permissions }} = this.props;
    const {location: { pathname }} = this.props;
    return (
        <Spin spinning={this.state.loading}>
        <div className={styles.root}>
        <div style={{ textAlign: "center" }}></div>
        <div className={styles.topBtn}>
          <div className={styles.left}>
            <Button
              style={{ marginRight: "15px" }}
              type="primary"
              onClick={() => {
                this.type = 0;
                this.province = null;
                this.initMapByLoading();
              }}
            >
              省级行政区划
            </Button>
            <Button
              style={{ marginRight: "15px" }}
              type="primary"
              onClick={() => {
                this.type = 1;
                this.city = null;
                this.initMapByLoading();
              }}
            >
              地市级行政区划
            </Button>
            <Button
              style={{ marginRight: "15px" }}
              type="primary"
              onClick={() => {
                this.type = 2;
                this.initMapByLoading();
              }}
            >
              区县级行政区划
            </Button>
            <Button type="primary" onClick={() => this.handleClickStreet()}>
              路网图
            </Button>
          </div>
          <Button type="primary" onClick={() => this.handleOnReturn()}>
            返回
          </Button>
        </div>
        <div className={styles.midMap}>
          <div
            id="container"
            style={{ width: "100%", height: "750px" }}
          ></div>
        </div>
      </div>
      </Spin>
    );
  }
}
